#include "MainWindow.hh"
#include <QtGui>

MainWindow::MainWindow(XmlClient* client, QString username, QString password):
    QMainWindow(),
    client(client),
    xmlInput(),
    xmlOutput(),
    password(password)
{
    QSplitter* splitter = new QSplitter();
    xmlInput = new QPlainTextEdit();
    xmlOutput = new QPlainTextEdit();
    QPushButton* button = new QPushButton();

    setCentralWidget(splitter);
    splitter->addWidget(xmlInput);
    splitter->addWidget(xmlOutput);
    splitter->addWidget(button);

    button->setText("Kuldes");
    connect(button, SIGNAL(clicked()), this, SLOT(send()));
    connect(
      client,
      SIGNAL(data_available(QString const&)),
      this,
      SLOT(setXmlOutput(QString const&))
    );


    if (username != "") {
        connect(
          client,   SIGNAL(data_available(QString const&)),
          this,     SLOT(send_password(QString const&))
        );
        client->send(
          "<auth>"
          " <request>"
          "  <username>" + username + "</username>"
          " </request>"
          "</auth>"
        );
    }
}

void MainWindow::send() {
    xmlOutput->setPlainText("");
    client->send(xmlInput->toPlainText());
}

void MainWindow::setXmlOutput(QString const& text) {
    xmlOutput->setPlainText(text);
}

void MainWindow::send_password(QString const& text) {
    (void)(text);
    client->send(
      "<auth>"
      " <response>"
      "  <hash>" + password + "</hash>"
      " </response>"
      "</auth>"
    );
    disconnect(
      client,   SIGNAL(data_available(QString const&)),
      this,     SLOT(send_password(QString const&))
    );
}



